<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Java EE," />





  <link rel="alternate" href="/atom.xml" title="Bingo's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="前言前阵子又重回老本行，开始了 JavaEE 的征程，为公司的技术部成立了 Java 组，实现了去年年底总结写的今年的期望。开始踩坑，发现每天早上第一次调用服务端的 API 时，都会有一个报错，查看日志发现是 jdbc 连接超时抛出异常。">
<meta name="keywords" content="Java EE">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaEE解决jdbc连接超时问题">
<meta property="og:url" content="https://bingozb.github.io/49.html">
<meta property="og:site_name" content="Bingo's Blog">
<meta property="og:description" content="前言前阵子又重回老本行，开始了 JavaEE 的征程，为公司的技术部成立了 Java 组，实现了去年年底总结写的今年的期望。开始踩坑，发现每天早上第一次调用服务端的 API 时，都会有一个报错，查看日志发现是 jdbc 连接超时抛出异常。">
<meta property="og:updated_time" content="2017-09-04T19:06:07.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaEE解决jdbc连接超时问题">
<meta name="twitter:description" content="前言前阵子又重回老本行，开始了 JavaEE 的征程，为公司的技术部成立了 Java 组，实现了去年年底总结写的今年的期望。开始踩坑，发现每天早上第一次调用服务端的 API 时，都会有一个报错，查看日志发现是 jdbc 连接超时抛出异常。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: 'JE30EVH7NI',
      apiKey: '862bb3deb9a3166ed99de0be6527f59c',
      indexName: 'blog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到关于「 ${query} 」的文章","hits_stats":"共找到 ${hits} 篇文章，花了 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://bingozb.github.io/49.html"/>





  <title>JavaEE解决jdbc连接超时问题 | Bingo's Blog</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c8a59b9753bce3ec58f81c89e2acce96";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Bingo's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay Hungry, Stay Foolish.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://bingozb.github.io/49.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Bingo">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Bingo's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                JavaEE解决jdbc连接超时问题
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-09-03T09:28:25+08:00">
                2017-09-03
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/战斗笔记/" itemprop="url" rel="index">
                    <span itemprop="name">战斗笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/49.html#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="49.html" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/49.html" class="leancloud_visitors" data-flag-title="JavaEE解决jdbc连接超时问题">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>前阵子又重回老本行，开始了 JavaEE 的征程，为公司的技术部成立了 Java 组，实现了去年年底总结写的今年的期望。开始踩坑，发现每天早上第一次调用服务端的 API 时，都会有一个报错，查看日志发现是 jdbc 连接超时抛出异常。</p>
<a id="more"></a>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection <span class="keyword">for</span> transaction;</div><div class="line">nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: </div><div class="line">The last packet successfully received from the server was <span class="number">145</span>,<span class="number">178</span>,<span class="number">488</span> milliseconds ago. </div><div class="line">The last packet sent successfully to the server was <span class="number">145</span>,<span class="number">178</span>,<span class="number">488</span> milliseconds ago. </div><div class="line">is longer than the server configured value of <span class="string">'wait_timeout'</span>.</div><div class="line">You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values <span class="keyword">for</span> client timeouts, or using the Connector/J connection property <span class="string">'autoReconnect=true'</span> to avoid <span class="keyword">this</span> problem.</div><div class="line">...</div></pre></td></tr></table></figure>
<h2 id="原因"><a href="#原因" class="headerlink" title="原因"></a>原因</h2><p>第一次出现这个问题时，我直接重启 Tomcat 就一切恢复正常了，但是又过了一天，问题再次出现。</p>
<p>仔细分析错误信息，问题肯定出在数据库连接部分，在网上查阅大量信息后，明确了问题的原因：<br>MySQL 对所有连接的有效时间默认为28800秒，正好8小时，也就是说，如果一个连接8小时没有请求和操作，就会自动断开。但是对于 Hibernate 来说，它的连接池并不知道它所管理的连接中是否有被 MySQL 断开的。如果一个程序要使用数据库连接，而 Hibernate 的连接池分配一个已经被 MySQL 断开了的给程序使用，那么便会出现错误。</p>
<p>为了证实确实是这个错误，我在本机上做了如下测试：首先部署项目并启动 Tomcat，修改系统时间，往后调1天。然后再调用 API 测试，果然出现这个问题。</p>
<p>MySQL + Hibernate 架构相当普遍，所以这个问题也相当普遍。有空建议做一下同样的测试，看看是否存在此问题，不要因为恰好用户多，访问量大而侥幸绕开了这个潜藏的问题。</p>
<h2 id="解决"><a href="#解决" class="headerlink" title="解决"></a>解决</h2><p>先说一种简单粗暴的解决办法，就是修改 JDBC 连接的 URL，添加 <code>autoReconnect=true</code> 这个参数，就能解决问题。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">jdbc:mysql:<span class="comment">//hostaddress:3306/schemaname?autoReconnect=true</span></div></pre></td></tr></table></figure>
<p>但是注意了，<strong>MYSQL5以上设置 <code>autoReconnect=true</code> 是无效的，只有4.x版本有效</strong>。当前使用的版本是5.7，所以还是得想想别的思路。</p>
<h3 id="思路"><a href="#思路" class="headerlink" title="思路"></a>思路</h3><p>思路1：增大 MySQL 的连接有效时间。<br>思路2：从程序自身出发，修改连接池的相关参数。</p>
<p>显然，思路1是不可行的，原因如下几点：</p>
<ul>
<li>不能保证这个问题绝对的解决，如果无访问时间够长，大于 MySQL 的连接有效时间，问题同样会发生。</li>
<li>遭到了 DBA 的强烈抵制，会影响其他的 MySQL 的性能。</li>
<li>一般情况下，我们都是将程序部署在别人的服务器上，不太方便去修改 MySQL 配置。</li>
</ul>
<p>所以网上的答案诸如 「 需要修改 my.conf，在 mysqld 后添加 wait_timeout=172800，interactive_timeout=172800 」是不可取的，不能从根本上解决问题。</p>
<p>那么只能从思路2入手了，修改连接池的相关参数。</p>
<p>Hibernate 支持如下的连接池：</p>
<ul>
<li>DriverManagerConnectionProvider：代表由 Hibernate 提供的默认的数据库连接池</li>
<li>C3P0ConnectionProvider：代表 C3P0 连接池</li>
<li>ProxoolConnectionProvider：代表 Proxool 连接池</li>
<li>DBCPConnectionProvider：代表 DBCP 连接池</li>
<li>DatasourceConnectionProvider：代表在受管理环境中由容器提供的数据源</li>
</ul>
<p>其中，默认连接池并不支持在分配一个连接时，测试其有效与否的功能。而 C3P0、Proxool、DBCP 都提供了这样的功能，正好可以解决上述问题。综合考虑各个连接池的效率、稳定性、易用性，决定换用 Proxool，它确实在各方面表现优良，方便配置。</p>
<h3 id="配置"><a href="#配置" class="headerlink" title="配置"></a>配置</h3><p>Proxool 连接池是 sourceforge 下的一个开源项目，这个项目提供一个健壮、易用的连接池，最为关键的是这个连接池提供监控的功能，方便易用，便于发现连接泄漏的情况。</p>
<h4 id="Hibernate配置文件"><a href="#Hibernate配置文件" class="headerlink" title="Hibernate配置文件"></a>Hibernate配置文件</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">session-factory</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"hibernate.connection.provider_class"</span>&gt;</span>org.hibernate.connection.ProxoolConnectionProvider<span class="tag">&lt;/<span class="name">property</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"hibernate.proxool.xml"</span>&gt;</span>proxool.xml<span class="tag">&lt;/<span class="name">property</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"hibernate.proxool.pool_alias"</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">property</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"show_sql"</span>&gt;</span>false<span class="tag">&lt;/<span class="name">property</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"dialect"</span>&gt;</span>org.hibernate.dialect.MySQLDialect<span class="tag">&lt;/<span class="name">property</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">mapping</span> <span class="attr">resource</span>=<span class="string">"ren/bingo/pojo/hbm.xml"</span> /&gt;</span></div><div class="line">...</div><div class="line"><span class="tag">&lt;/<span class="name">session-factory</span>&gt;</span></div></pre></td></tr></table></figure>
<p>其中各属性含义如下：</p>
<ul>
<li>hibernate.connection.provider_class : 指明使用 Proxool 连接池。</li>
<li>hibernate.proxool.xml : 指明 Proxool 配置文件所在位置，这里与 Hibernate 的配置文件在同一目录下。</li>
<li>hibernate.proxool.pool_alias : 指明要使用的 proxool.xml 中定义的 proxool 别名。</li>
</ul>
<h4 id="Proxool配置文件-proxool-xml"><a href="#Proxool配置文件-proxool-xml" class="headerlink" title="Proxool配置文件 (proxool.xml)"></a>Proxool配置文件 (proxool.xml)</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="php"><span class="meta">&lt;?</span>xml version=<span class="string">"1.0"</span> encoding=<span class="string">"UTF-8"</span><span class="meta">?&gt;</span></span></div><div class="line"><span class="comment">&lt;!-- the proxool configuration can be embedded within your own application's. Anything outside the "proxool" tag is ignored. --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">something-else-entirely</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">proxool</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- proxool别名 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">alias</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">alias</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- 数据库连接Url --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">driver-url</span>&gt;</span></div><div class="line"> jdbc:mysql://localhost:3306/yourDatebase?useUnicode=true&amp;characterEncoding=UTF-8</div><div class="line"><span class="tag">&lt;/<span class="name">driver-url</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- JDBC驱动名称 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">driver-class</span>&gt;</span>com.mysql.jdbc.Driver<span class="tag">&lt;/<span class="name">driver-class</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- 数据库连接帐号 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">driver-properties</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"user"</span> <span class="attr">value</span>=<span class="string">"root"</span> /&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"password"</span> <span class="attr">value</span>=<span class="string">"password"</span> /&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">driver-properties</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- proxool自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回收,超时的销毁 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">house-keeping-sleep-time</span>&gt;</span>90000<span class="tag">&lt;/<span class="name">house-keeping-sleep-time</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- 指因未有空闲连接可以分配而在队列中等候的最大请求数,超过这个请求数的用户连接就不会被接受 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">maximum-new-connections</span>&gt;</span>20<span class="tag">&lt;/<span class="name">maximum-new-connections</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- 最少保持的空闲连接数 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">prototype-count</span>&gt;</span>3<span class="tag">&lt;/<span class="name">prototype-count</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- 允许最大连接数,超过了这个连接，再有请求时，就排在队列中等候，最大的等待请求数由maximum-new-connections决定 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">maximum-connection-count</span>&gt;</span>20<span class="tag">&lt;/<span class="name">maximum-connection-count</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- 最小连接数 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">minimum-connection-count</span>&gt;</span>3<span class="tag">&lt;/<span class="name">minimum-connection-count</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- 在分配连接前后是否进行有效性测试，这个是解决本问题的关键 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">test-before-use</span>&gt;</span>true<span class="tag">&lt;/<span class="name">test-before-use</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">test-after-use</span>&gt;</span>true<span class="tag">&lt;/<span class="name">test-after-use</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- 用于测试的SQL语句 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">house-keeping-test-sql</span>&gt;</span>SELECT CURRENT_USER<span class="tag">&lt;/<span class="name">house-keeping-test-sql</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">proxool</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">something-else-entirely</span>&gt;</span></div></pre></td></tr></table></figure>
<p>其中，解决问题最关键是这两行，在分配连接前后是否进行有效性测试。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">test-before-use</span>&gt;</span>true<span class="tag">&lt;/<span class="name">test-before-use</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">test-after-use</span>&gt;</span>true<span class="tag">&lt;/<span class="name">test-after-use</span>&gt;</span></div></pre></td></tr></table></figure>
<p>而下面的 test-sql 则是进行测试的 SQL 语句。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">house-keeping-test-sql</span>&gt;</span>SELECT CURRENT_USER<span class="tag">&lt;/<span class="name">house-keeping-test-sql</span>&gt;</span></div></pre></td></tr></table></figure>
<p>这种思路就是分配连接前后，进行有效性测试，如果无效，则新建一个连接再返回。</p>
<h4 id="web-xml"><a href="#web-xml" class="headerlink" title="web.xml"></a>web.xml</h4><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">servlet</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>ServletConfigurator<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">servlet-class</span>&gt;</span>org.logicalcobwebs.proxool.configuration.ServletConfigurator<span class="tag">&lt;/<span class="name">servlet-class</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">init-param</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>xmlFile<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>WEB-INF/proxool.xml<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">load-on-startup</span>&gt;</span>1<span class="tag">&lt;/<span class="name">load-on-startup</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">servlet</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">servlet</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>proxool<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">servlet-class</span>&gt;</span>org.logicalcobwebs.proxool.admin.servlet.AdminServlet<span class="tag">&lt;/<span class="name">servlet-class</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">servlet</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>proxool<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/proxool<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></div></pre></td></tr></table></figure>
<p>自此，Proxool 配置成功。重新启动 Tomcat，再次做上述测试，问题已解决。</p>
<p>如果想要用 Spring 以 dataSource 方式使用 proxool 连接池，则稍微改一下写法。在 Spring 的 applicationContext.xml 中定义 dataSource bean 即可，property 参数还是一样的。</p>
<h2 id="后话"><a href="#后话" class="headerlink" title="后话"></a>后话</h2><p><strong>Question</strong> :<br>现在 SSM 框架这么火，谁还用 SSH ？不用 Hibernate 而使用 Mybatis 怎么办？</p>
<p><strong>Answer</strong> :<br>本文只是讲清问题的原因，以及解决的思路。不同的集成框架，解决问题的办法总是大同小异的，网上搜索肯定可以找到满意的资料。当然，作为一个很热衷于归档的人，我肯定也会做一篇专题总结的。</p>
<p>既然说到火，那就再火一点，干脆改用 SSM 搭配堪称最好的数据库连接池 Druid。下一篇博文我会详细地介绍阿里巴巴的这个开源项目，以及 Druid 的使用。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <ul class="post-copyright">
    <li class="post-copyright-author">
      <strong>本文作者：</strong>
      Bingo
    </li>
    <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://bingozb.github.io/49.html" title="JavaEE解决jdbc连接超时问题">https://bingozb.github.io/49.html</a>
    </li>
    <li class="post-copyright-license">
      <strong>版权声明： </strong>
      本博客所有文章除特别声明外，均采用 MIT 许可协议。转载请注明出处！
    </li>
  </ul>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java-EE/" rel="tag"># Java EE</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/51.html" rel="next" title="phantomjs实现服务端屏幕截图">
                <i class="fa fa-chevron-left"></i> phantomjs实现服务端屏幕截图
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/48.html" rel="prev" title="解决iOS上传ipa失败(-22421)问题">
                解决iOS上传ipa失败(-22421)问题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.jpg"
               alt="Bingo" />
          <p class="site-author-name" itemprop="name">Bingo</p>
           
              <p class="site-description motion-element" itemprop="description">He who hesitates is lost.</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">55</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">22</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/bingozb" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://coding.net/u/bingozb" target="_blank" title="Coding">
                  
                    <i class="fa fa-fw fa-git"></i>
                  
                  Coding
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/bingo_v587" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.facebook.com/profile.php?id=100013406670597" target="_blank" title="Facebook">
                  
                    <i class="fa fa-fw fa-facebook"></i>
                  
                  Facebook
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#原因"><span class="nav-number">2.</span> <span class="nav-text">原因</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#解决"><span class="nav-number">3.</span> <span class="nav-text">解决</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#思路"><span class="nav-number">3.1.</span> <span class="nav-text">思路</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#配置"><span class="nav-number">3.2.</span> <span class="nav-text">配置</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Hibernate配置文件"><span class="nav-number">3.2.1.</span> <span class="nav-text">Hibernate配置文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Proxool配置文件-proxool-xml"><span class="nav-number">3.2.2.</span> <span class="nav-text">Proxool配置文件 (proxool.xml)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#web-xml"><span class="nav-number">3.2.3.</span> <span class="nav-text">web.xml</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#后话"><span class="nav-number">4.</span> <span class="nav-text">后话</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  Copyright © 
  <span itemprop="copyrightYear">2017
  </span>
  <span class="author" itemprop="copyrightHolder">Bingo
  </span>
  All rights reserved.
</div>
        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytcdzpa3';
      var conf = 'c0c6117021d1cea9f11629100efd8446';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (search_path.endsWith("json")) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      $('#local-search-input').focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("A9MeTkIR49W9kOOSvkggsXge-gzGzoHsz", "HaIEOSDyxpcjwOjRjCYxiWjA");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

</body>
</html>
